﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Data.SqlServerCe;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Controls
{
    public partial class SearchMusic_Control : UserControl
    {
        //Connection, should be passed in from containing class of component
        private SqlCeConnection mConnection = null;
        //Query results use this data reader
        private SqlCeDataReader mDataReader = null;

        //Interface to set connection

        public SearchMusic_Control()
        {
            InitializeComponent();
        }

        public SqlCeConnection Connection
        {
            set { mConnection = value; }
        }

        private void searchButton_Click(object sender, EventArgs e)
        {
            if (searchTextBox.Text.Length <= 0)
            {
                MessageBox.Show("You must enter a value to search for.");
            }
            else
            {
                resultsListBox.Items.Clear();
                SqlCeCommand search;
                if (songRadioButton.Checked)
                {
                    String songName = searchTextBox.Text;
                    songName = songName.Replace("'", "''");
                    search = new SqlCeCommand(String.Format("SELECT SongName, Artist, Genre FROM Library WHERE SongName='{0}';", new Object[] { songName }), mConnection);
                    mDataReader = search.ExecuteReader();
                    while (mDataReader.Read())
                    {
                        String s = mDataReader.GetString(1) + ", " + mDataReader.GetString(0);
                        resultsListBox.Items.Add(s);
                    }
                    if (resultsListBox.Items.Count < 1)
                    {
                        resultsListBox.Items.Add("No match found");
                    }
                }
                else if (artistRadioButton.Checked)
                {
                    String artist = (searchTextBox.Text.Length > 0 ? searchTextBox.Text : null);
                    search = new SqlCeCommand(String.Format("SELECT SongName, Artist, Genre FROM Library WHERE Artist='{0}';", new Object[] { artist }), mConnection);
                    mDataReader = search.ExecuteReader();
                    while (mDataReader.Read())
                    {
                        String s = mDataReader.GetString(1) + ", " + mDataReader.GetString(0);
                        resultsListBox.Items.Add(s);
                    }
                    if (resultsListBox.Items.Count < 1)
                    {
                        resultsListBox.Items.Add("No match found");
                    }
                }
            }
        }
    }
}
